<?php

namespace app\api\controller\v1;

use think\Db;
use think\Loader;
use Think\Log;

Loader::import('alipay.AopSdk',EXTEND_PATH,'.php');


class Pay extends Base
{
    public function pay()
    {
        if ($this->request->isPost()) {
            $data = input('post.');
            $this->isLogin($data);
            if (empty($data)) {
                return show(400, "参数不能为空！");
            }
            if (empty($data['uid'])) return show(400, '用户id不能为空！');
            if (empty($data['out_trade_no'])) return show(400, '订单不能为空！');
            if (!isset($data['payway'])) return show(400, '支付方式不能为空！');
            $orderdata = Db::name('Order')->where(array('out_trade_no' => $data['out_trade_no'], 'uid' => $data['uid']))->find();
            if (empty($orderdata)) return show(400, '此订单不存在！');
            if ($orderdata['ispay'] == 1) return show(400, '此订单已支付或以完成！不能重复支付！');

            if ($data['payway'] == 1) {
                $config = config("pay.WXCONF");
                $wxappid = $config['appid'];
                $mch_id = $config['mch_id'];
                $notify_url = 'http://www.qnn.com/api/v1/WxPay/weipayverify';
                $wxkey = 'Kk81NhsJPAiqMSns9fTFTgAot2GuRaRi';
                $wechatAppPay = new wechatAppPay($wxappid, $mch_id, $notify_url, $wxkey);
                $params = array();
                $params['body'] = 'APP-在线支付';
                $params['out_trade_no'] = $orderdata['out_trade_no'];
//                $orderdata['total_price'] = '0.01';
                $params['total_fee'] = (int)($orderdata['total_price'] * 100);
                $params['trade_type'] = 'APP';
                $wx_result = $wechatAppPay->unifiedOrder($params);
                if ($wx_result['return_code'] == "SUCCESS") {
                    $sign_array = array();
                    $sign_array['appid'] = $wx_result['appid'];
                    $sign_array['partnerid'] = $wx_result['mch_id'];
                    $sign_array['prepayid'] = $wx_result['prepay_id'];
                    $sign_array['package'] = 'Sign=WXPay';
                    $sign_array['noncestr'] = $wx_result['nonce_str'];
                    $sign_array['timestamp'] = time();
                    $sign_two = $wechatAppPay->MakeSign($sign_array);
                    $sign_array['sign'] = $sign_two;
                    return show(200, "获取支付参数成功", $sign_array);
                } else {
                    return show(400, "获取支付参数错误");
                }
            } elseif ($data['payway'] == '2') {
                //实例化支付接口
                $aop = new \AopClient();

                $aop->gatewayUrl = "https://openapi.alipaydev.com/gateway.do"; //支付宝网关
                $config = config("pay.ALICONF");
                $aop->appId = $config['ALIPAYAPPID'];

                $aop->rsaPrivateKey = $config['ALIPAYPRIKEY'];

                $aop->alipayrsaPublicKey = $config['ALIPAYPUBLICKEY'];

                $aop->apiVersion = "1.0";

                $aop->signType = "RSA2";

//                $aop->postCharset = "UTF-8";
                $aop->charset = "UTF-8";

                $aop->format = "json";

                //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay

                $appRequest = new \AlipayTradeAppPayRequest();
                $orderdata['total_price'] = '0.01';
                //SDK已经封装掉了公共参数，这里只需要传入业务参数
                $bizcontent = json_encode([

                    "body" => '全能助手金币购买服务',  //订单描述

                    "subject" => '全能助手-金币购买',   //订单标题

                    "timeout_express" => "30m",

                    "out_trade_no" => $orderdata["out_trade_no"], //商户网站唯一订单号

                    "total_amount" => $orderdata['total_price']*100, //订单总金额

                    "product_code" => "QUICK_MSECURITY_PAY", //固定值

                ]);
                $url = "http://www.qnn.com/api/v1/pay/notifyurl";
                $appRequest->setNotifyUrl($url);  //设置异步通知地址

                $appRequest->setBizContent($bizcontent);

                //这里和普通的接口调用不同，使用的是sdkExecute

                $response = $aop->sdkExecute($appRequest);

                //htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题

                // $str = htmlspecialchars($response);//就是orderString 可以直接给客户端请求，无需再做处理。
                return $response;
                // 如果最后有问题可以尝试把htmlspecialchars方法去掉，直接返回$response
//                return show1(200, "返回支付信息成功！", $response);
            }
        } else {
            return show(400, "请求方式有误！");
        }


    }

    /**
     * 支付宝回掉地址
     * @return [type] [description]
     */
    public function notifyurl()
    {
        $aop = new \AopClient;
        $config = config("pay.ALICONF");
        $aop->alipayrsaPublicKey = $config['ALIPAYPUBLICKEY'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if (!$flag) {
            Log::write("支付宝notify通知验证失败" . $_POST['trade_status_no' . "验证失败"]);
        }
        if ($_POST['trade_status'] == "TRADE_SUCCESS") {
            $savedata['ispay'] = 1;
            $savedata['pay_time'] = time();
            Db::name('Order')->where(array('out_trade_no' => $_POST['out_trade_no']))->save($savedata);

        } elseif ($_POST['trade_status'] == 'TRADE_CLOSED') {
            return $this->cacelOrder($_POST['out_trade_no']);
        }
    }
/*
    public function rechargenotifyurl()
    {
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvw91N4FesI2k/CjNhNJdAPLFzqcnwRkb0gYKMr+ogiLKkvhSaAsLIB9sQReQVFbpRTl56Ol8m0//hK7tuGpiL0eol7D0GczN2+e1JD0bTPKhYCI7iQ2EBtseQw56PBzbIf3pjM7ACfRAz2JXGdl6QWPzzyNTZYnKFqXKB/Nk3dqIBw0KFXESmJSqX9TcqhtzPm2anDY2nlmAw1SWzR1HeRi+V4KbTrCAvZKBPl6NBUuMFDkQ1+TBd650L1KoOoETZOUdv4wSYCvEtss7DganAk9406M4ubK9nqtOy+NFcM4mDwkj0frJ9nS6ZoKsAseoyXO8rsZLcKj9RamD6mRnbQIDAQAB";
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if (!$flag) {
            Log::write("支付宝notify通知验证失败" . $_POST['trade_status_no' . "验证失败"]);
        }
        if ($_POST['trade_status'] == "TRADE_SUCCESS") {
            $model = M('User');
            $reModel = M('recharge');
            $res = $reModel->where(array('order_code' => $_POST['out_trade_no']))->find();
            $logdata['uid'] = $res['uid'];
            $logdata['total'] = $res['money'];
            $logdata['id'] = $res['order_code'];
            $logdata['yprice'] = $res['money'];
            $this->addUserLog($logdata, 3, 0);
            $reModel->where(array('order_code' => $_POST['out_trade_no']))->save(array('status' => 1));
            $model->where(array('order_code' => $_POST['out_trade_no']))->setInc("wallet", $res['money']);
        }
        echo 'success';
    }

    public function addnotifyurl()
    {
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvw91N4FesI2k/CjNhNJdAPLFzqcnwRkb0gYKMr+ogiLKkvhSaAsLIB9sQReQVFbpRTl56Ol8m0//hK7tuGpiL0eol7D0GczN2+e1JD0bTPKhYCI7iQ2EBtseQw56PBzbIf3pjM7ACfRAz2JXGdl6QWPzzyNTZYnKFqXKB/Nk3dqIBw0KFXESmJSqX9TcqhtzPm2anDY2nlmAw1SWzR1HeRi+V4KbTrCAvZKBPl6NBUuMFDkQ1+TBd650L1KoOoETZOUdv4wSYCvEtss7DganAk9406M4ubK9nqtOy+NFcM4mDwkj0frJ9nS6ZoKsAseoyXO8rsZLcKj9RamD6mRnbQIDAQAB";
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if (!$flag) {
            Log::write("支付宝notify通知验证失败" . $_POST['trade_status_no' . "验证失败"]);
        }
        if ($_POST['trade_status'] == "TRADE_SUCCESS") {
            $model = M('Demand');
            $addpriceModel = M('Addprice');
            $res = $addpriceModel->where(array('order_code' => $_POST['out_trade_no']))->find();
            $logdata['uid'] = $res['uid'];
            $logdata['total'] = $res['money'];
            $logdata['id'] = $res['order_code'];
            $logdata['yprice'] = $res['money'];
            $this->addUserLog($logdata, 6, 0);
            $addpriceModel->where(array('order_code' => $_POST['out_trade_no']))->save(array('status' => 1));
            $model->where(array('add_code' => $_POST['out_trade_no']))->setInc("addprice", $res['money']);
        }
        echo 'success';
    }
*/
}